/**
 * Magic grid pager plugin 1.1
 * Author: Mac_J@boarsoft.com
 * Need: core.js
 */
mac.pager = function(self, config) {
	self.pagerLength = config.pagerLength;
	self.loadPage = config.loadPage;
	self.lg = '<span class="ui-state-default">&gt;&gt;|</span>';
	self.ng = '<span class="ui-state-default">&gt;&gt;</span>';
	self.pg = '<span class="ui-state-default">&lt;&lt;</span>';
	self.fg = '<span class="ui-state-default">|&lt;&lt;</span>';
	// self.lp = "";
	self.np = '<span class="ui-state-default">&gt;</span>';
	self.pp = '<span class="ui-state-default">&lt;</span>';
	// self.fp = "";
	//
	self.update = function(total, pageSize, pageCount, pageNo) {
		self.empty();
		//
		self.total = total;
		self.pageCount = pageCount;
		self.pageNo = pageNo;
		self.pageSize = pageSize;
		//
		self.append(mac.msg(Msg.pager.page, [ self.total, self.pageNo,
				self.pageCount ]));
		self.append('&nbsp;');
		//
		var hf = Math.floor(self.pagerLength / 2);
		var hm = self.pagerLength % 2;
		var start = self.pageNo - hf;
		if (start > self.pageCount - self.pagerLength + 1) {
			start = self.pageCount - self.pagerLength + 1;
		}
		if (start < 1) {
			start = 1;
		}
		var end = start + self.pagerLength;
		if (end > self.pageCount + 1) {
			end = self.pageCount + 1;
		}
		if (start > 1) {
			var a = $('<span action="1" class="pageNo"></span>');
			a.append(self.fg).appendTo(self);
		}
		if (start > self.pagerLength) {
			var a = $('<span class="pageNo"></span>');
			var h = start - hf + (hm > 0) ? 0 : 1;
			a.attr('action', h).append(self.pg);
		}
		for ( var i = start; i < end; i++) {
			var a = $('<span class="pageNo"></span>');
			if (i != self.pageNo)
				a.attr('action', i);
			a.append(i).appendTo(self);
		}
		if (end <= self.pageCount - self.pagerLength) {
			var a = $('<span class="pageNo"></span>');
			a.attr('action', (end + hf)).append(self.ng).appendTo(self);
		}
		if (end < self.pageCount) {
			var a = $('<span class="pageNo"></span>');
			a.attr('action', self.pageCount).append(self.lg).appendTo(self);
		}
		self.children('span[action]').click(function() {
			self.pageNo = $(this).attr('action');
			self.loadPage.call(self, self.pageNo, self.pageSize);
		});
		var pageNo = $('<input type="text" name="pageNo" />');
		pageNo.attr('maxlength', ('' + self.pageCount).length);
		pageNo.change(function() {
			this.value = (this.value <= self.pageCount) ? this.value
					: self.pageCount;
			this.value = (this.value > 0) ? this.value : 1;
		});
		self.append(pageNo);
		var btnGo = $('<span class="button"></span>').click(function() {
			var pn = pageNo.val();
			if (!pn || isNaN(pn) || pn > self.pageCount)
				pn = 0;
			self.pageNo = pn;
			self.loadPage.call(self, self.pageNo, self.pageSize);
		}).append(Msg.pager.go);
		self.append(btnGo);
	};
	return self;
}